package stockPrice;

import interfaces.StockPriceInfo;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.TimerTask;

import exceptions.WrongShareName;
import mainBoerse.Share;
import mainBoerse.UpdateTimer;

public abstract class StockPriceProvider implements StockPriceInfo {
	
	//private static Share[] SHARES = new Share[]{new Share("BMW" , 10), new Share("AUDI" , 10), new Share("VW" , 7)};
	//private static ArrayList<Share> SHARESlist = new ArrayList<Share>(Arrays.asList(new Share("YOTTA" , 4), new Share("ZETA", 6), new Share("BMW" , 10), new Share("AUDI" , 10), new Share("VW" , 7)));
	private static ArrayList<Share> SHARESlist = new ArrayList<Share>(Arrays.asList(new Share("BMW" , 10), new Share("AUDI", 1), new Share("VW" , 7)/*, new Share("PORSCHE", 1)*/));
	public void addShare(String name, long course) {
		SHARESlist.add(new Share(name, course));
	}
	
	@Override
	public boolean isShareListed(String shareName) throws WrongShareName {
		
		for(Share share : StockPriceProvider.getSHARES()) {
			if(share.getAktienName().equals(shareName)) return true;
		}	
		
		throw new WrongShareName("wrong share name");
		//return false;
	}
	
	public static void addNewShare(String shareName) {
		StockPriceProvider.SHARESlist.add(new Share(shareName, 4));
	}

	@Override
	public float getCurrentShareRate(String shareName) throws WrongShareName {
		
		return this.getShare(shareName).getAktienKurs();
	}

	@Override
	public ArrayList<Share> getAllSharesAsSnapShot() {
		//Collections.sort(SHARESlist, new NameComparator());
		Collections.sort(SHARESlist,(Share a, Share b) -> a.getAktienName().compareTo(b.getAktienName()));
		return SHARESlist;
	}

	
	public Share getShare(String shareName) throws WrongShareName {
		int index = 0;
		try {
			if (isShareListed(shareName)) {
				for (int i = 0; i < StockPriceProvider.getSHARES().size(); i++) {
					if (StockPriceProvider.getSHARES().get(i).getAktienName().equals(shareName))
						index = i;
				}
			}
		} catch (WrongShareName e) {
			throw e;
		}

		return StockPriceProvider.getSHARES().get(index);

	}
	
	
	public void startUpdate() {
		UpdateTimer.startTimingWithOwnTimerTask(new TimerTask(){
			public void run () {
				updateShareRates();
			}
		},1000, 2000);
	}
	

	
	public abstract void updateShareRates();
	
	protected abstract void updateShareRate(Share share) throws WrongShareName;

	public static ArrayList<Share> getSHARES() {
		//Collections.sort(SHARESlist, new NameComparator());
		Collections.sort(SHARESlist,(Share a, Share b) -> a.getAktienName().compareTo(b.getAktienName()));
		return SHARESlist;
	}

	/*public void setSHARES(Share[] sHARES) {
		SHARES = sHARES;
	}*/
}

/*class NameComparator implements Comparator<Share> {

	@Override
	public int compare(Share arg0, Share arg1) {
		
		return arg0.getAktienName().compareToIgnoreCase(arg1.getAktienName());
	}
	
}*/
